<template>
  <div class="login-container">
    <div class="card">
      <h2>{{ isLogin ? "登录" : "注册" }}</h2>
      <form @submit.prevent="onSubmit">
        <div class="form-group">
          <label for="username">用户名</label>
          <input
            id="username"
            v-model="form.username"
            type="text"
            placeholder="请输入用户名"
            required
          />
        </div>

        <div class="form-group" v-if="!isLogin">
          <label for="email">邮箱</label>
          <input
            id="email"
            v-model="form.email"
            type="email"
            placeholder="请输入邮箱"
            required
          />
        </div>

        <div class="form-group">
          <label for="password">密码</label>
          <input
            id="password"
            v-model="form.password"
            type="password"
            placeholder="请输入密码"
            required
          />
        </div>

        <div class="form-group" v-if="!isLogin">
          <label for="confirmPassword">确认密码</label>
          <input
            id="confirmPassword"
            v-model="form.confirmPassword"
            type="password"
            placeholder="请再次输入密码"
            required
          />
        </div>

        <!-- 验证码输入框 + 获取验证码按钮 -->
        <div class="form-group" v-if="!isLogin">
          <label for="verificationCode">验证码</label>
          <div class="verification-code-wrapper">
            <input
              id="verificationCode"
              v-model="form.verificationCode"
              type="text"
              placeholder="请输入验证码"
              required
              class="input-code"
            />
            <button
              type="button"
              class="btn-code"
              @click="sendCode"
              :disabled="countdown > 0"
            >
              {{ countdown > 0 ? countdown + '秒后重发' : '获取验证码' }}
            </button>
          </div>
        </div>

        <button type="submit" class="btn">{{ isLogin ? "登录" : "注册" }}</button>
      </form>

      <p class="toggle-text">
        {{ isLogin ? "没有账号？" : "已有账号？" }}
        <a href="#" @click.prevent="toggleMode">{{ isLogin ? "去注册" : "去登录" }}</a>
      </p>
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from "vue";
import { useRouter } from "vue-router";
import  api from "@/utils/request"

const router = useRouter();//引入router实例

const isLogin = ref(true);

const form = reactive({
  username: "",
  email: "",
  password: "",
  confirmPassword: "",
  verificationCode: "",
});

function toggleMode() {
  isLogin.value = !isLogin.value;
  form.username = "";
  form.email = "";
  form.password = "";
  form.confirmPassword = "";
}

async function onSubmit() {
  if (!form.username.trim()) {
    alert("用户名不能为空");
    return;
  }
  if (!form.password) {
    alert("请输入密码");
    return;
  }
  if (!isLogin.value) {
    if (!form.email.includes("@")) {
      alert("请输入有效邮箱");
      return;
    }
    if (form.password !== form.confirmPassword) {
      alert("两次输入的密码不一致");
      return;
    }
  }

  const login_payload = {
    username: form.username,
    password: form.password,
  };

  const register_payload = {
    username: form.username,
    password: form.password,
    email: form.email,
    code: form.verificationCode,
  };

  if (isLogin.value) {
    // ToDo: 调用登录接口
    try {
      const res = await api.post("/auth/login", login_payload);
      console.log(res)
      console.log("登录的响应：", res.code);
      
      if (res.code === 200) {
        alert("登录成功");
        // 如果有 token 就保存
        if (res.token) {
          localStorage.setItem("token", res.token);
        }
        alert(`登录账号：${form.username}`);
        router.push("/recommend");
      } else {
        alert(`登录失败：${res}`);
      }
    } catch (error: any) {
      console.error("登录失败", error);
      alert("服务器连接失败或用户名/密码错误");
    }
  } else {
    // ToDo: 调用注册接口
    // ✅ 注册接口调用
    try {
      const res = await api.post("/auth/register", register_payload);
      console.log("注册的响应：", res);

      if (res.code === 200) {
        alert("注册成功，请登录");
        toggleMode(); // 切换到登录界面
      } else {
        alert(`注册失败：${res}`);
      }
    } catch (error: any) {
      console.error("注册失败", error);
      alert("服务器连接失败，注册失败");
    }
    // alert(`注册账号：${form.username}，邮箱：${form.email}`);
  }
}

const countdown = ref(0);
let timer: number | null = null;

async function sendCode() {
    if (!form.email || !form.email.includes("@")) {
      alert("请先输入有效的邮箱地址！");
      return;
    }

    const get_ver = {
      email: form.email,
    }

    try {
      const res = await api.post("/verify/send_code", get_ver);
      console.log("验证码发送响应：", res.code);

      if (res.code === 200) {
        alert("验证码已发送，请查收邮箱！");
        startCountdown();
      } else {
        alert(`发送失败：${res}`);
      }
    } catch (error) {
      console.error("验证码发送失败：", error);
      alert("发送验证码时出错，请稍后再试");
    }
  }

  function startCountdown() {
    countdown.value = 60;
    timer = window.setInterval(() => {
      countdown.value--;
      if (countdown.value <= 0 && timer !== null) {
        clearInterval(timer);
        timer = null;
      }
    }, 1000);
}

</script>

<style src="./Login.css"></style>
